<?php
// like_post.php
session_start();

// 数据库连接代码...
$dbHost = 'localhost';
$dbName = 'db';
$dbUser = 'root';
$dbPass = '';

// 检查是否已经登录
if (!isset($_SESSION['user_id'])) {
    die(json_encode(['error' => '用户未登录']));
}

// 获取POST数据
$post_id = isset($_POST['post_id']) ? intval($_POST['post_id']) : 0;

// 检查POST数据
if ($post_id <= 0) {
    die(json_encode(['error' => '无效的动态ID']));
}

// 检查用户是否已经点赞过
$sql = "SELECT * FROM likes WHERE post_id = ? AND user_id = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("ii", $post_id, $_SESSION['user_id']);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows > 0) {
    // 用户已经点赞过，这里可以选择实现取消点赞的逻辑
    $sql = "DELETE FROM likes WHERE post_id = ? AND user_id = ?";
    $stmt->prepare($sql);
    $stmt->bind_param("ii", $post_id, $_SESSION['user_id']);
    $stmt->execute();
    echo json_encode(['success' => true]);
} else {
    // 插入新的点赞记录
    $sql = "INSERT INTO likes (post_id, user_id) VALUES (?, ?)";
    $stmt->prepare($sql);
    $stmt->bind_param("ii", $post_id, $_SESSION['user_id']);
    $stmt->execute();
    echo json_encode(['success' => true]);
}

$stmt->close();
$conn->close();
?>